package cn.yujiago.miaosha.service.impl;

import cn.yujiago.miaosha.component.UserContext;
import cn.yujiago.miaosha.constant.UserConstant;
import cn.yujiago.miaosha.dto.CodeMsg;
import cn.yujiago.miaosha.dto.Result;
import cn.yujiago.miaosha.entity.User;
import cn.yujiago.miaosha.exception.UserException;
import cn.yujiago.miaosha.mapper.UserMapper;
import cn.yujiago.miaosha.redis.RedisService;
import cn.yujiago.miaosha.redis.UserKey;
import cn.yujiago.miaosha.service.UserService;
import cn.yujiago.miaosha.util.CookieUtil;
import cn.yujiago.miaosha.util.MyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public Result<User> login(HttpServletResponse response, User user) {
        // 对密码进行二次加密
        String password = MyStringUtil.md5(user.getUsername() + user.getPassword());

        User loginUser = userMapper.selectUser(user.getUsername(), password);

        if(loginUser == null){
            throw new UserException(CodeMsg.LOGIN_ERROR);
        }

        String token = MyStringUtil.uuid();
        // 将token写回客户端
        CookieUtil.setValueByKey(response, UserConstant.COOKIE_NAME_TOKEN, token, 60*60*24);
        // 将登录的用户缓存到redis
        redisService.set(UserKey.getByName, token, loginUser);
        // 将登录的用户与本地线程绑定
        UserContext.setUser(loginUser);
        return Result.success(loginUser);
    }

    @Override
    public User getByToken(HttpServletResponse httpServletResponse, String token) {
        User user = redisService.get(UserKey.getByName, token, User.class);
        // 延长有效期
        if(user != null){
            // 将token写回客户端
            CookieUtil.setValueByKey(httpServletResponse, UserConstant.COOKIE_NAME_TOKEN, token, 60*60*24);
            // 将登录的用户缓存到redis
            redisService.set(UserKey.getByName, token, user);
            // 将登录的用户与本地线程绑定
            UserContext.setUser(user);
        }
        return user;
    }

    public static void main(String[] args){
        System.out.println(MyStringUtil.md5("zhangsan" + MyStringUtil.md5("123456")));
    }

}
